﻿using ComPortUser;
using NPOI.HSSF.Record.Chart;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using static NPOI.POIFS.Crypt.CryptoFunctions;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;

namespace Module_Debug
{
    public partial class Demuraip : Form
    {
        int flag = 0, cell_flag = 0;
        string strtmp = "";
        string head_str = "";
        string end_str = "";
        string strtmp_sub0 = "";
        string strtmp_sub1 = "";
        string strtmp_sub2 = "";
        string strtmp_sub3 = "";

        /*字符串按频率分割*/
        private string str_concat(string str_data, string comboBox_value)
        {
            int num;
            StringBuilder sb = new StringBuilder();

            int.TryParse(comboBox_value.Substring(0, 1), out num);
            num--;
            sb.Append(str_data.Substring(81 * 16 * num, 81 * 16));
            return sb.ToString();
        }

        /*字符串按RGB分割*/
        private string rgb_concat(string str_data, string comboBox6_value)
        {
            int num = 1;
            string str_r = "";
            string str_g = "";
            string str_b = "";

            StringBuilder sb = new StringBuilder();
            int.TryParse(comboBox6_value.Substring(0, 2), out num);
            num--;

            str_r += str_data.Substring(27 * 16 * 0, 27 * 16);
            str_g += str_data.Substring(27 * 16 * 1, 27 * 16);
            str_b += str_data.Substring(27 * 16 * 2, 27 * 16);

            string[] str_r_sub = str_r.Split(new Char[] { ',' });
            string[] str_g_sub = str_g.Split(new Char[] { ',' });
            string[] str_b_sub = str_b.Split(new Char[] { ',' });

            for (int i = 0; i < 9; i++)
            {
                sb.Append(str_r_sub[(num) + 16 * i]);
                sb.Append(",");
                sb.Append(str_g_sub[(num) + 16 * i]);
                sb.Append(",");
                sb.Append(str_b_sub[(num) + 16 * i]);
                sb.Append(",");
            }

            return sb.ToString();
        }

        /*数据显示*/
        private void Data_show(string[] arrtmp)
        {
            try
            {
                int i = 0;
                int frontRowCount = 1;
                DMR_dataGridView_r.Rows[i].Cells[0 + frontRowCount].Value = arrtmp[0];
                DMR_dataGridView_r.Rows[i].Cells[1 + frontRowCount].Value = arrtmp[3];
                DMR_dataGridView_r.Rows[i].Cells[2 + frontRowCount].Value = arrtmp[6];
                DMR_dataGridView_r.Rows[i].Cells[3 + frontRowCount].Value = arrtmp[9];
                DMR_dataGridView_r.Rows[i].Cells[4 + frontRowCount].Value = arrtmp[12];
                DMR_dataGridView_r.Rows[i].Cells[5 + frontRowCount].Value = arrtmp[15];
                DMR_dataGridView_r.Rows[i].Cells[6 + frontRowCount].Value = arrtmp[18];
                DMR_dataGridView_r.Rows[i].Cells[7 + frontRowCount].Value = arrtmp[21];
                DMR_dataGridView_r.Rows[i].Cells[8 + frontRowCount].Value = arrtmp[24];

                //------------------------------------
                DMR_dataGridView_g.Rows[i].Cells[0 + frontRowCount].Value = arrtmp[1];
                DMR_dataGridView_g.Rows[i].Cells[1 + frontRowCount].Value = arrtmp[4];
                DMR_dataGridView_g.Rows[i].Cells[2 + frontRowCount].Value = arrtmp[7];
                DMR_dataGridView_g.Rows[i].Cells[3 + frontRowCount].Value = arrtmp[10];
                DMR_dataGridView_g.Rows[i].Cells[4 + frontRowCount].Value = arrtmp[13];
                DMR_dataGridView_g.Rows[i].Cells[5 + frontRowCount].Value = arrtmp[16];
                DMR_dataGridView_g.Rows[i].Cells[6 + frontRowCount].Value = arrtmp[19];
                DMR_dataGridView_g.Rows[i].Cells[7 + frontRowCount].Value = arrtmp[22];
                DMR_dataGridView_g.Rows[i].Cells[8 + frontRowCount].Value = arrtmp[25];

                //------------------------------------
                DMR_dataGridView_b.Rows[i].Cells[0 + frontRowCount].Value = arrtmp[2];
                DMR_dataGridView_b.Rows[i].Cells[1 + frontRowCount].Value = arrtmp[5];
                DMR_dataGridView_b.Rows[i].Cells[2 + frontRowCount].Value = arrtmp[8];
                DMR_dataGridView_b.Rows[i].Cells[3 + frontRowCount].Value = arrtmp[11];
                DMR_dataGridView_b.Rows[i].Cells[4 + frontRowCount].Value = arrtmp[14];
                DMR_dataGridView_b.Rows[i].Cells[5 + frontRowCount].Value = arrtmp[17];
                DMR_dataGridView_b.Rows[i].Cells[6 + frontRowCount].Value = arrtmp[20];
                DMR_dataGridView_b.Rows[i].Cells[7 + frontRowCount].Value = arrtmp[23];
                DMR_dataGridView_b.Rows[i].Cells[8 + frontRowCount].Value = arrtmp[26];

                int line = 1;//
                showmsg("数据导入OK！");
            }
            catch
            {
                MessageBox.Show("数据导入时发生错误！", "提示：");
            }
        }

        /*原文件处理*/
        private string File_deal(out int count, string file_addr)
        {
            int Line_Count = 0;
            string strLine, file_str = "", str_out = "";
            string[] arrtmp;

            FileStream fs = new FileStream(file_addr, FileMode.Open, FileAccess.Read); // 以只读模式打开文件 fname是文件路径
            StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK")); // 读取文件内容 并指定编码格式
            streamReader.BaseStream.Seek(0, SeekOrigin.Begin); // 从头读取
            while ((strLine = streamReader.ReadLine()) != null)
            {
                if ( Line_Count<4 )
                {
                    head_str += strLine + "\r\n";
                }

                if (Line_Count>10 && (strLine[1]!='7'|| strLine[2] != '8'))
                {
                    end_str += strLine + "\r\n";
                }

                strLine = FilterNonHexCharacters(strLine);
                file_str = file_str + strLine + "\r";
                Line_Count++;
            }
            fs.Close(); //关闭流
            streamReader.Close();
            str_out += file_str;
            arrtmp = file_str.Split(new Char[] { '\r' });
            for (int i = 0; i < Line_Count; i++)
            {
                CheckForGreaterThanF(arrtmp[i], i);
            }
            count = Line_Count;
            return file_str;
        }

        /*按IC类型进行分类处理*/
        private string IC_sort(string ic_id, string filePath)
        {
            string str_out_sub = "";
            string str_head = "FE,22\r\n5F,02\r\n";
            string str_end = "\r\n";
            switch (ic_id)
            {
                case "01. RM692k0":
                    string str_pre = File_deal(out int count, filePath);
                    string[] str_filter_split = str_pre.Split(new Char[] { '\r' });
                    string str_out = "";
                    for (int i = 0; i < count; i++)
                    {
                        if (str_filter_split[i][0] == '7' && (str_filter_split[i][1] == '7' || str_filter_split[i][1] == '8'))
                        {
                            str_out += InsertCommaEveryTwoChars(str_filter_split[i].Substring(2, 256)) + ",";
                        }
                        else
                        {
                            if (i < 10)
                            {
                                if (('A' <= str_filter_split[i][0] && str_filter_split[i][0] <= 'F') || ('0' <= str_filter_split[i][0] && str_filter_split[i][0] <= '9'))
                                {
                                    str_head += InsertCommaEveryTwoChars(str_filter_split[i].Substring(0, 4)) + "\r\n";
                                }
                            }
                            if (i > 45)
                            {
                                if (('A' <= str_filter_split[i][0] && str_filter_split[i][0] <= 'F') || ('0' <= str_filter_split[i][0] && str_filter_split[i][0] <= '9'))
                                {
                                    str_end += InsertCommaEveryTwoChars(str_filter_split[i].Substring(0, 4)) + "\r\n";
                                }
                                else
                                {
                                    str_end += "FF,FF,FF,14" + "\r\n";
                                }
                            }
                        }
                    }
                    str_out_sub += str_out;
                    break;
                default:
                    break;
            }

            textBox2.Text = str_head;
            str_end += "FE,22\r\n5F,00";
            txtDMR7778End.Text = str_end;
            return str_out_sub;
        }

        /*将修改后的数据保存成文件*/
        private string Data_out()
        {
            string str = "";
            string test = "";
            string strtmp_sub = "";
            int num;
            int.TryParse(comboBox6.SelectedItem.ToString().Substring(0, 2), out num);
            num--;
            StringBuilder sb = new StringBuilder();

            for (int n = 1; n < 10; n++)
            {
                sb.Append(DMR_dataGridView_r.Rows[0].Cells[n].Value.ToString());
                sb.Append(",");
            }
            for (int n = 1; n < 10; n++)
            {
                sb.Append(DMR_dataGridView_g.Rows[0].Cells[n].Value.ToString());
                sb.Append(",");
            }
            for (int n = 1; n < 10; n++)
            {
                sb.Append(DMR_dataGridView_b.Rows[0].Cells[n].Value.ToString());
                sb.Append(",");
            }

            string[] arrtmp = sb.ToString().Split(new Char[] { ',' });
            test = str_concat(strtmp, HFR_comboBox.SelectedItem.ToString());// 频率
            string[] arrtmp_1 = test.Split(new Char[] { ',' });

            for (int i = 0; i < 9; i++)
            {
                arrtmp_1[(num) + 16 * i] = arrtmp[i];
                arrtmp_1[(num) + 16 * i + 16 * 9] = arrtmp[i + 9];
                arrtmp_1[(num) + 16 * i + 16 * 9 * 2] = arrtmp[i + 18];
            }

            StringBuilder sb_sub = new StringBuilder();

            for (int i = 0; i < 16 * 9 * 3; i++)
            {
                sb_sub.Append(arrtmp_1[i]);
                sb_sub.Append(",");
            }

            return sb_sub.ToString();
        }

        /*文件格式的规范*/
        static string InsertCommaEveryTwoChars(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < input.Length; i += 2)
            {
                if (i > 0)
                {
                    sb.Append(',');
                }

                if (i + 1 < input.Length)
                {
                    sb.Append(input.Substring(i, 2));
                }
                else
                {
                    sb.Append(input[i]);
                }
            }

            return sb.ToString();
        }

        /*文件筛选出非16字节的字符*/
        static string FilterNonHexCharacters(string input)
        {
            string hexPattern = @"[0-9A-Za-z]";

            MatchCollection matches = Regex.Matches(input, hexPattern);
            StringBuilder sb = new StringBuilder();
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                sb.Append(match.Value);
            }
            return sb.ToString();
        }

        /*保存开头为77，78的数据行*/
        private void CheckForGreaterThanF(string input, int line)
        {
            int[] num = new int[10];// 在这里存放所有不在允许范围内的值，找出
            int max = 0, min = 0;
            int j = 0;
            for (int i = 0; i < input.Length; i++)
            {
                if ((input[i] > 'f' && input[i] <= 'z') || (input[i] > 'F' && input[i] <= 'Z'))
                {
                    if (j == 0)
                    {
                        min = i;
                        j++;
                    }
                    max = i;
                }
            }
            if (j == 1)
            {
                txtDMR7788.Text += line + ":" + input.Substring(min, (max - min + 2)) + "\r\n";
            }
        }

        public Demuraip()
        {
            InitializeComponent();
        }
        private byte[] Send_buf = new byte[1];
        CRC16 CRCData = new CRC16();
        private void btnSendsetting_Click(object sender, EventArgs e)
        {
            //Button btnTmp = (Button)sender;
            const byte SendbufLength = 60;
            {
                Send_buf = new byte[SendbufLength];
                //Button btnTmp = (Button)sender;
                Setting.TempRecord.cmdLen = SendbufLength;
                Send_buf[0] = 0x66;   //DemuraIPConfig
                Send_buf[2] = SendbufLength - 4; //数据长度
                if (!frmMain.frmain.comPort.IsOpen)
                {
                    try
                    {
                        frmMain.frmain.comPort.PortName = Detection.GetComNum();
                        frmMain.frmain.comPort.BaudRate = Setting.ComSet.comBaudRate;
                        frmMain.frmain.openSerialPort(true);
                    }
                    catch
                    {
                        MessageBox.Show("没有搜索到串口！", "错误提示");
                    }
                }
                //switch (btnTmp.Name)
                {
                    //case "btnlogic_go":
                    {
                        Send_buf[1] = 0x01;   // 预留标志位

                        //Send_buf[3] = (byte)((int)(numDemuraLUTnumber.Value) >> 8); 
                        //Send_buf[4] = (byte)((int)(numDemuraLUTnumber.Value) );

                        //Send_buf[5] = (byte)((((byte)numBlockmode.Value) << 2) + (((byte)cmbUpsamplemode.SelectedIndex) << 1) + (((byte)cmbAlgmode.SelectedIndex) << 0));

                        //Send_buf[6] = (byte)((int)numMinialpha.Value >> 8);
                        //Send_buf[7] = (byte)((int)numMinialpha.Value);
                        //Send_buf[8] = (byte)((int)numMinbeta.Value >> 8);
                        //Send_buf[9] = (byte)((int)numMinbeta.Value);
                        //Send_buf[10] = (byte)((int)numMingamma.Value >> 8);
                        //Send_buf[11] = (byte)((int)numMingamma.Value);

                        //Send_buf[12] = (byte)((int)numStepalpha.Value >> 8);
                        //Send_buf[13] = (byte)((int)numStepalpha.Value);
                        //Send_buf[14] = (byte)((int)numStepbeta.Value >> 8);
                        //Send_buf[15] = (byte)((int)numStepbeta.Value);
                        //Send_buf[16] = (byte)((int)numStepgamma.Value >> 8);
                        //Send_buf[17] = (byte)((int)numStepgamma.Value);

                        //Send_buf[18] = (byte)((((byte)cmbShiftalphamode.SelectedIndex) << 4) + (((byte)cmbShiftbetamode.SelectedIndex) << 2) + (((byte)cmbShiftgammamode.SelectedIndex) << 0));

                        //Send_buf[19] = (byte)((int)numvt.Value >> 8);
                        //Send_buf[20] = (byte)((int)numvt.Value);

                        //Send_buf[21] = (byte)((int)numht.Value >> 8);
                        //Send_buf[22] = (byte)((int)numht.Value);

                        //Send_buf[23] = (byte)((int)numNearalpha.Value);
                        //Send_buf[24] = (byte)(((int)numNearbeta.Value << 4) + ((int)numNeargamma.Value));

                        //Send_buf[25] = (byte)((int)numAlphat1.Value);
                        //Send_buf[26] = (byte)((int)numAlphat2.Value);
                        //Send_buf[27] = (byte)((int)numAlphat3.Value);

                        //Send_buf[28] = (byte)((int)numBetat1.Value);
                        //Send_buf[29] = (byte)((int)numBetat2.Value);
                        //Send_buf[30] = (byte)((int)numBetat3.Value);

                        //Send_buf[31] = (byte)((int)numGammat1.Value);
                        //Send_buf[32] = (byte)((int)numGammat2.Value);
                        //Send_buf[33] = (byte)((int)numGammat3.Value);

                        //Send_buf[34] = (byte)((int)numAlphaaddroffset.Value >> 16);
                        //Send_buf[35] = (byte)((int)numAlphaaddroffset.Value >> 8);
                        //Send_buf[36] = (byte)((int)numAlphaaddroffset.Value);
                        //Send_buf[37] = (byte)((int)numAlphabitoffset.Value);

                        //Send_buf[38] = (byte)((int)numBetaaddroffset.Value >> 16);
                        //Send_buf[39] = (byte)((int)numBetaaddroffset.Value >> 8);
                        //Send_buf[40] = (byte)((int)numBetaaddroffset.Value);
                        //Send_buf[41] = (byte)((int)numBetabitoffset.Value);

                        //Send_buf[42] = (byte)((int)numGammaaddroffset.Value >> 16);
                        //Send_buf[43] = (byte)((int)numGammaaddroffset.Value >> 8);
                        //Send_buf[44] = (byte)((int)numGammaaddroffset.Value);
                        //Send_buf[45] = (byte)((int)numGammabitoffset.Value);

                        //Send_buf[46] = (byte)((int)numBitdepthalpha.Value);
                        //Send_buf[47] = (byte)((int)numBitdepthbeta.Value);
                        //Send_buf[48] = (byte)((int)numBitdepthgamma.Value);

                        //Send_buf[49] = (byte)((int)numMaxValalpha.Value);
                        //Send_buf[50] = (byte)((int)numMaxValbeta.Value);
                        //Send_buf[51] = (byte)((int)numMaxValgamma.Value);

                        Send_buf[57] = 0xFA;
                    }
                    //break;
                    // default:
                    //    break;
                }

                CRCData.CalculateCrc16(Send_buf, out Send_buf[SendbufLength - 2], out Send_buf[SendbufLength - 1]);
                try
                {
                    frmMain.frmain.comPort.Write(Send_buf, 0, SendbufLength);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                }
            }
        }

        private void Demuraip_Load(object sender, EventArgs e)
        {
            //cmbAlgmode.SelectedIndex = 0;
            //cmbShiftalphamode.SelectedIndex = 0;
            //cmbShiftbetamode.SelectedIndex = 0;
            //cmbShiftgammamode.SelectedIndex = 0;
            //cmbUpsamplemode.SelectedIndex = 0;
            //DemuraipconfigLoad();
            ReadDemuraipcfg("./Demuraip/demuraip.dcfg");
            HFR_comboBox.SelectedItem = "1. HFR0";
            comboBox6.SelectedItem = "01. T0";
            comboBox7.SelectedItem = "01. RM692k0";
        }

        //private void btnSendDmrLUTNumber_Click(object sender, EventArgs e)
        //{
        //    // if (chkDemuraIPTest.Checked)
        //    {
        //        Send_buf = new byte[25];
        //        Setting.TempRecord.cmdLen = 25;
        //        Send_buf[0] = 0x0A; //LCD配置标志
        //        Send_buf[1] = 0xFB; //Demura IP 用 DBV 标志位
        //        Send_buf[2] = 0x15;  // byte.Parse(arr0.Length.ToString());

        //        Send_buf[3] = (byte)((int)(numDemuraLUTnumber.Value) >> 24);
        //        Send_buf[4] = (byte)((int)(numDemuraLUTnumber.Value) >> 16);
        //        Send_buf[5] = (byte)((int)(numDemuraLUTnumber.Value) >> 8);
        //        Send_buf[6] = (byte)((int)(numDemuraLUTnumber.Value) >> 0);

        //        CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
        //        try
        //        {
        //            frmMain.frmain.comPort.Write(Send_buf, 0, 25);
        //        }
        //        catch
        //        {
        //            MessageBox.Show("串口有误，请检查", "错误");
        //        }
        //    }
        //}
        private void btnSaveAsDMRCfg_Click(object sender, EventArgs e)
        {
            //byte[] InitiateFile = new byte[32];
            //byte[] DemuraIPParameters = new byte[4024];
            //string strTmp;
            //byte[] Tepbyte = System.Text.Encoding.Default.GetBytes("abcd");
            string cfgaddr;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog(); //对话框
            byte[] FileHead = System.Text.Encoding.Default.GetBytes("----------Demuraip.dcfg----------");
            byte[] InitiateFile = new byte[FileHead.Length];
            saveFileDialog1.FileName = "Demuraip.dcfg";
            saveFileDialog1.Filter = "DemuraIP Configure File(*.dcfg)|*.dcfg";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                cfgaddr = saveFileDialog1.FileName;
                //System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();//输出文件
                //Array.Clear(InitiateFile, 0, 32);
                SaveDMRCfg(cfgaddr);
            }
        }
        private void btnSaveDMRCfg_Click(object sender, EventArgs e)
        {
            SaveDMRCfg("./Demuraip/Demuraip.dcfg");
        }
        private void SaveDMRCfg(string cfgaddr)
        {
            //byte[] DemuraIPParameters = new byte[4024];
            string strTmp;
            byte[] FileHead = System.Text.Encoding.Default.GetBytes("---*---Demuraip.dcfg---*---");
            try
            {
                System.IO.FileStream fs = File.OpenWrite(cfgaddr);   //  //输出文件

                //Array.Clear(InitiateFile, 0, 32);
                //Array.Copy(FileHead, InitiateFile, FileHead.Length);
                //fs.Write(InitiateFile, 0, InitiateFile.Length);       //0x00-0x1F:文件头，"Demuraip.dcfg"
                fs.Write(FileHead, 0, FileHead.Length);       //0x00-0x1F:文件头，"Demuraip.dcfg"

                //strTmp = "\r\n" + numBlockmode.Value + "\r\n" + cmbUpsamplemode.SelectedIndex;
                //strTmp += "\r\n" + cmbAlgmode.SelectedIndex;
                //strTmp += "\r\n" + numMinialpha.Value;
                //strTmp += "\r\n" + numMinbeta.Value;
                //strTmp += "\r\n" + numMingamma.Value;
                //strTmp += "\r\n" + numStepalpha.Value;
                //strTmp += "\r\n" + numStepbeta.Value;
                //strTmp += "\r\n" + numStepgamma.Value;
                //strTmp += "\r\n" + cmbShiftalphamode.SelectedIndex;
                //strTmp += "\r\n" + cmbShiftbetamode.SelectedIndex;
                //strTmp += "\r\n" + cmbShiftgammamode.SelectedIndex;
                //strTmp += "\r\n" + numvt.Value;
                //strTmp += "\r\n" + numht.Value;
                //strTmp += "\r\n" + numNearalpha.Value;
                //strTmp += "\r\n" + numNearbeta.Value;
                //strTmp += "\r\n" + numNeargamma.Value;
                //strTmp += "\r\n" + numAlphat1.Value;
                //strTmp += "\r\n" + numAlphat2.Value;
                //strTmp += "\r\n" + numAlphat3.Value;
                //strTmp += "\r\n" + numBetat1.Value;
                //strTmp += "\r\n" + numBetat2.Value;
                //strTmp += "\r\n" + numBetat3.Value;
                //strTmp += "\r\n" + numGammat1.Value;
                //strTmp += "\r\n" + numGammat2.Value;
                //strTmp += "\r\n" + numGammat3.Value;
                //strTmp += "\r\n" + numAlphaaddroffset.Value;
                //strTmp += "\r\n" + numAlphabitoffset.Value;
                //strTmp += "\r\n" + numBetaaddroffset.Value;
                //strTmp += "\r\n" + numBetabitoffset.Value;
                //strTmp += "\r\n" + numGammaaddroffset.Value;
                //strTmp += "\r\n" + numGammabitoffset.Value;
                //strTmp += "\r\n" + numBitdepthalpha.Value;
                //strTmp += "\r\n" + numBitdepthbeta.Value;
                //strTmp += "\r\n" + numBitdepthgamma.Value;
                //strTmp += "\r\n" + numMaxValalpha.Value;
                //strTmp += "\r\n" + numMaxValbeta.Value;
                //strTmp += "\r\n" + numMaxValgamma.Value;

                //strTmp += "\r\n" + numDemuraLUTnumber.Value;   //Demura LUT number

                //strTmp += "\r\n";
                //byte[] Tepbyte = System.Text.Encoding.Default.GetBytes(strTmp);

                //fs.Write(Tepbyte, 0, Tepbyte.Length);
                //fs.Dispose(); //释放资源               
                //fs.Close();
            }
            catch
            {
                MessageBox.Show("--保存错误--");
            }
        }
        List<string> lines;
        //private List<byte> buffer = new List<byte>(4096);//默认分配1/16页内存，并始终限制不允许超过 
        private void ReadDemuraipcfg(string addr)
        {
            lines = new List<string>();
            //FileStream fs = new FileStream(Application.StartupPath + "\\x_ViewTrix\\Fun1.txt", FileMode.Open)
            try
            {
                FileStream fs = new FileStream(addr, FileMode.Open);
                StreamReader rd = new StreamReader(fs);
                string s;
                //读入文件所有行，存放到List<string>集合中
                while ((s = rd.ReadLine()) != null)
                {
                    lines.Add(s);
                }
                rd.Dispose();
                rd.Close();
                fs.Dispose();
                fs.Close();

                //numBlockmode.Value = Int32.Parse(lines[1]);
                //cmbUpsamplemode.SelectedIndex = Int32.Parse(lines[2]);
                //cmbAlgmode.SelectedIndex = Int32.Parse(lines[3]);
                //numMinialpha.Value = Int32.Parse(lines[4]);
                //numMinbeta.Value = Int32.Parse(lines[5]);
                //numMingamma.Value = Int32.Parse(lines[6]);
                //numStepalpha.Value = Int32.Parse(lines[7]);
                //numStepbeta.Value = Int32.Parse(lines[8]);
                //numStepgamma.Value = Int32.Parse(lines[9]);
                //cmbShiftalphamode.SelectedIndex = Int32.Parse(lines[10]);
                //cmbShiftbetamode.SelectedIndex = Int32.Parse(lines[11]);
                //cmbShiftgammamode.SelectedIndex = Int32.Parse(lines[12]);
                //numvt.Value = Int32.Parse(lines[13]);
                //numht.Value = Int32.Parse(lines[14]);
                //numNearalpha.Value = Int32.Parse(lines[15]);
                //numNearbeta.Value = Int32.Parse(lines[16]);
                //numNeargamma.Value = Int32.Parse(lines[17]);
                //numAlphat1.Value = Int32.Parse(lines[18]);
                //numAlphat2.Value = Int32.Parse(lines[19]);
                //numAlphat3.Value = Int32.Parse(lines[20]);
                //numBetat1.Value = Int32.Parse(lines[21]);
                //numBetat2.Value = Int32.Parse(lines[22]);
                //numBetat3.Value = Int32.Parse(lines[23]);
                //numGammat1.Value = Int32.Parse(lines[24]);
                //numGammat2.Value = Int32.Parse(lines[25]);
                //numGammat3.Value = Int32.Parse(lines[26]);
                //numAlphaaddroffset.Value = Int32.Parse(lines[27]);
                //numAlphabitoffset.Value = Int32.Parse(lines[28]);
                //numBetaaddroffset.Value = Int32.Parse(lines[29]);
                //numBetabitoffset.Value = Int32.Parse(lines[30]);
                //numGammaaddroffset.Value = Int32.Parse(lines[31]);
                //numGammabitoffset.Value = Int32.Parse(lines[32]);
                //numBitdepthalpha.Value = Int32.Parse(lines[33]);
                //numBitdepthbeta.Value = Int32.Parse(lines[34]);
                //numBitdepthgamma.Value = Int32.Parse(lines[35]);
                //numMaxValalpha.Value = Int32.Parse(lines[36]);
                //numMaxValbeta.Value = Int32.Parse(lines[37]);
                //numMaxValgamma.Value = Int32.Parse(lines[38]);
                //numDemuraLUTnumber.Value = Int32.Parse(lines[39]);
            }
            catch
            {

            }
        }
        private void btnLoadDMRCfg_Click(object sender, EventArgs e)
        {
            string path;
            OpenFileDialog fldb = new OpenFileDialog();

            fldb.Filter = @"dcfg文件(*.dcfg)|*.dcfg|所有文件(*.*)|*.*"; ;
            fldb.Title = "载入DemuraIP Configure File";
            //defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            //if (defaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                // fldb.SelectedPath = defaultfilePath;
            }
            //fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("----没选择吧???----");
                return;
            }
            //defaultfilePath = fldb.SelectedPath;
            path = fldb.FileName;
            ReadDemuraipcfg(path);
        }

        //private void btnSendsetting_MouseEnter(object sender, EventArgs e)
        //{
        //    ToolTip p = new ToolTip();
        //    p.ShowAlways = true;
        //    p.SetToolTip(this.btnSendsetting, "发送除了LUT之外的所有参数");
        //}

        private void btnReload_Demura_File_Click(object sender, EventArgs e)
        {

        }

        private void BIN_load_path(object sender, KeyEventArgs e)
        {

        }

        private void listBox3_Demura_File_DoubleClick(object sender, EventArgs e)
        {
            label1.Text += "128";
        }

        // 数据拆分


        private void btnLoadDMRCfg_Click_1(object sender, EventArgs e)
        {
            string test = "";
            string filePath = "";
            string str_pre = "";
            head_str = "";
            end_str = "";
            strtmp = "";
            strtmp_sub0 = "";
            strtmp_sub1 = "";
            strtmp_sub2 = "";
            strtmp_sub3 = "";

            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title = "选择文件";
                openFileDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
                openFileDialog.FilterIndex = 1;
                openFileDialog.Multiselect = false;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    filePath += openFileDialog.FileName;
                }
            }
            catch { Console.WriteLine("没有选择文件"); }

            if (!string.IsNullOrEmpty(filePath))
            {
                textBox1.Text = filePath;// 文件路径
                strtmp += IC_sort(comboBox7.Text.ToString(), filePath);// 依据ic型号进行数据处理
                this.DMR_dataGridView_r.Rows.Clear();
                this.DMR_dataGridView_g.Rows.Clear();
                this.DMR_dataGridView_b.Rows.Clear();

                dbvGridView1.Rows[0].Cells[0].Value = "DBV";
                float[] tepArrLUM = new float[] { 0.0f, 2.0f, 10.0f, 30.0f, 50.0f, 89.8f, 90.0f, 150.0f, 270.0f, 600.0f, 800.0f, 2000.0f, 0.0f, 2.0f, 30.0f, 50.0f };
                int[] tepArrDBV = new int[] { 0, 1, 0x13d, 0x25f, 0x325, 0x451, 0x452, 0x5ab, 0x8e1, 0xbcd, 0xdbb, 0xf7e, 0, 1, 0x25f, 0x325 };

                for (int i = 0; i < 16; i++)
                {
                    dbvGridView1.Columns[i + 1].HeaderText = tepArrLUM[i].ToString();
                    dbvGridView1.Rows[0].Cells[i + 1].Value = tepArrDBV[i].ToString("X");
                }

                test = str_concat(strtmp, HFR_comboBox.SelectedItem.ToString()); // 频率分割
                string strtmp_sub = rgb_concat(test, comboBox6.SelectedItem.ToString()); // 亮度分割
                string[] arrtmp = strtmp_sub.Split(new Char[] { ',' });

                // 数据显示
                Data_show(arrtmp);
                flag = 1;
            }
        }

        private uint[,,] Dmrcfg = new uint[16, 9, 3];//保存当前Gammavalue
        private void btnLoadDMRCFG_Click(object sender, EventArgs e)
        {
            //txt51Dbv_TextChanged(null, null);
            //for (byte nn = 0; nn < TotalGammaNum; nn++)
            //{
            //    gammaindex = nn;
            //    btnSaveGamma_Click(btnLoadGamma_Auto, null);
            //}
            //GPN = (byte)Point_Hi3288.Length; // 获取Gamma绑点数量
            //GammavalMove(0, 0, GammaValx, GammaValue); //把第一组Gamma从GammaValx搬出至GammaValue
            //if (chkGammaGridViewFresh.Checked)   // 刷新UI界面GammaValue值显示
            {
                this.DMR_dataGridView_r.Rows.Clear();
                for (byte i = 0; i < 9; i++)
                {
                    DataGirdShow(i, Dmrcfg[i, i, 0], Dmrcfg[i, i, 0], Dmrcfg[i, i, 0]);
                }
            }
        }
        public void DataGirdShow(byte index, double RRR, double GGG, double BBB)        //UI 表格显示 R/G/B对应Gamma寄存器值
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;

            DataGridViewRow Row1 = new DataGridViewRow();

            Row_Accum = this.DMR_dataGridView_r.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                Current_Index = this.DMR_dataGridView_r.SelectedCells[0].RowIndex;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.DMR_dataGridView_r.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.DMR_dataGridView_r.Rows[Row_Accum - 1].Selected = false;
                        this.DMR_dataGridView_r.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.DMR_dataGridView_r.Rows.Add(Row1);
            }
            this.DMR_dataGridView_r.Rows[Row_Accum].Cells[0].Value = index + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            this.DMR_dataGridView_r.Rows[Row_Accum].Cells[1].Value = 1;
            this.DMR_dataGridView_r.Rows[Row_Accum].Cells[2].Value = RRR;
            this.DMR_dataGridView_r.Rows[Row_Accum].Cells[3].Value = GGG;
            this.DMR_dataGridView_r.Rows[Row_Accum].Cells[4].Value = BBB;

            if (Row_flag == 1)
            {
                Row_flag = 0;
                Row_Accum = this.DMR_dataGridView_r.Rows.Count - 1;
                this.DMR_dataGridView_r.Rows[Current_Index].Selected = false;
                this.DMR_dataGridView_r.Rows[Row_Accum - 1].Selected = true;
            }
            DMR_dataGridView_r.FirstDisplayedScrollingRowIndex = DMR_dataGridView_r.RowCount - 1;
        }
        bool debugprint = false;
        private void showmsg(string str, params byte[] mesgshowLevel)
        {
            byte MsgshowLevel;
            if (mesgshowLevel != null && mesgshowLevel.Length > 0)
            {
                MsgshowLevel = mesgshowLevel[0];
            }
            else { MsgshowLevel = 0; }
            if ((MsgshowLevel == 0) || ((MsgshowLevel > 0) && (debugprint)))
            {
                frmMain.frmain.textBox1.Text += str + "\r\n";
                frmMain.frmain.textBox1.SelectionStart = frmMain.frmain.textBox1.Text.Length;
                frmMain.frmain.textBox1.ScrollToCaret();//滚动到光标处
                if (frmMain.frmain.textBox1.Lines.Length > 5000) frmMain.frmain.textBox1.Clear();
            }
        }

        private void btnSendCFG_Click(object sender, EventArgs e)
        {
            frmMain.frmain.txtProcessDrivercode(txtDMR7788.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
            if (rdo_lp.Checked)
            {

                frmMain.frmain.SendCmd(0);
            }
            else
            {
                frmMain.frmain.SendCmd(4);
            }
        }

        private void btnPreProcess_Click(object sender, EventArgs e)
        {
            string tepstr = "", strtepr = "";
            int start = 0, length = 128 * 3, num, i, xx;

            int.TryParse(HFR_comboBox.SelectedItem.ToString().Substring(0, 1), out num);
            if (num > 1)
            {
                tepstr += strtmp.Substring(0, 16 * 9 * 9 * (num - 1)); // 获取频率之前数值
            }
            tepstr += Data_out();// 获取当前的频率的RGB值
            xx = tepstr.Length;
            try
            {
                strtepr += "77," + tepstr.Substring(start, length - 1) + "\r\n";
                for (i = 0; i < (xx / length - 1); i++)
                {
                    strtepr += "78," + tepstr.Substring(length * (i + 1), length - 1) + "\r\n";

                }
                strtepr += "78," + tepstr.Substring(length * (i + 1), 16 * 9 * 3 * 3 * num - length * (i + 1) - 1) + "\r\n";
                txtDMR7788.Text = textBox2.Text + strtepr + txtDMR7778End.Text;
            }
            catch { }
        }
        int rowIndex = 0, columnIndex = 0;
        private void DMR_dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (flag == 1 && e.ColumnIndex > 0 && e.RowIndex == 0)
            {
                DataGridView btnTmp = (DataGridView)sender;
                int tep = 0;

                DMR_dataGridView_r.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.White;
                DMR_dataGridView_g.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.White;
                DMR_dataGridView_b.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.White;

                rowIndex = e.RowIndex;       // 横坐标
                columnIndex = e.ColumnIndex; // 纵坐标

                DMR_dataGridView_r.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.GreenYellow;
                DMR_dataGridView_g.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.GreenYellow;
                DMR_dataGridView_b.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.GreenYellow;

                DMR_dataGridView_r.ClearSelection();
                DMR_dataGridView_g.ClearSelection();
                DMR_dataGridView_b.ClearSelection();

                int.TryParse(DMR_dataGridView_r.Rows[rowIndex].Cells[columnIndex].Value.ToString(), System.Globalization.NumberStyles.HexNumber, null, out tep);
                TrackBar_DMRcfg_R.Value = tep;

                int.TryParse(DMR_dataGridView_g.Rows[rowIndex].Cells[columnIndex].Value.ToString(), System.Globalization.NumberStyles.HexNumber, null, out tep);
                TrackBar_DMRcfg_G.Value = tep;// 传递值给滑轮控件

                int.TryParse(DMR_dataGridView_b.Rows[rowIndex].Cells[columnIndex].Value.ToString(), System.Globalization.NumberStyles.HexNumber, null, out tep);
                TrackBar_DMRcfg_B.Value = tep;
                cell_flag = 1;
            }
            else if (e.RowIndex != 0)
            {
                MessageBox.Show("点击错误", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("点击load，加载数据", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private bool isMouseOverControl = false;

        private void numericUpDown1_MouseEnter(object sender, EventArgs e)
        {
            isMouseOverControl = true;
        }

        private void numericUpDown1_MouseLeave(object sender, EventArgs e)
        {
            isMouseOverControl = false;
        }

        private void TrackBar_DMRcfg_Scroll(object sender, EventArgs e)
        {
            if (columnIndex > 0 && flag == 1 && cell_flag == 1)
            {
                TrackBar btnTmp = (TrackBar)sender;
                int tep = 0;
                switch (btnTmp.Name)
                {
                    case "TrackBar_DMRcfg_R":
                        {
                            showmsg(TrackBar_DMRcfg_R.Value.ToString());
                            DMR_dataGridView_r.Rows[rowIndex].Cells[columnIndex].Value = ((byte)(TrackBar_DMRcfg_R.Value)).ToString("x2");
                        }
                        break;
                    case "TrackBar_DMRcfg_G":
                        {
                            showmsg(TrackBar_DMRcfg_G.Value.ToString());
                            DMR_dataGridView_g.Rows[rowIndex].Cells[columnIndex].Value = ((byte)(TrackBar_DMRcfg_G.Value)).ToString("x2");
                        }
                        break;
                    case "TrackBar_DMRcfg_B":
                        {
                            showmsg(TrackBar_DMRcfg_B.Value.ToString());
                            DMR_dataGridView_b.Rows[rowIndex].Cells[columnIndex].Value = ((byte)(TrackBar_DMRcfg_B.Value)).ToString("x2");
                        }
                        break;
                    default: { break; }
                }
            }
        }

        private void TrackBar_DMRcfg_ValueChanged(object sender, EventArgs e)
        {
            if (columnIndex > 0 && flag == 1 && cell_flag == 1)
            {
                TrackBar btnTmp = (TrackBar)sender;
                int tep = 0;
                switch (btnTmp.Name)
                {
                    case "TrackBar_DMRcfg_R":
                        {
                            if (isMouseOverControl)
                            {
                                try
                                {
                                    timer_sendcfg.Stop();
                                    DMR_dataGridView_r.Rows[rowIndex].Cells[columnIndex].Value = ((byte)(TrackBar_DMRcfg_R.Value)).ToString("x2");
                                    timer_sendcfg.Interval = 300;
                                    timer_sendcfg.Start();
                                    isMouseOverControl = false;
                                }
                                catch
                                {
                                    showmsg("错了");
                                    isMouseOverControl = false;
                                }
                            }
                        }
                        break;
                    case "TrackBar_DMRcfg_G":
                        {
                            if (isMouseOverControl)
                            {
                                try
                                {
                                    timer_sendcfg.Stop();
                                    DMR_dataGridView_g.Rows[rowIndex].Cells[columnIndex].Value = ((byte)(TrackBar_DMRcfg_G.Value)).ToString("x2");
                                    timer_sendcfg.Interval = 300;
                                    timer_sendcfg.Start();
                                    isMouseOverControl = false;
                                }
                                catch
                                {
                                    showmsg("错了");
                                    isMouseOverControl = false;
                                }
                            }
                        }
                        break;
                    case "TrackBar_DMRcfg_B":
                        {
                            if (isMouseOverControl)
                            {
                                try
                                {
                                    timer_sendcfg.Stop();
                                    DMR_dataGridView_b.Rows[rowIndex].Cells[columnIndex].Value = ((byte)(TrackBar_DMRcfg_B.Value)).ToString("x2");
                                    timer_sendcfg.Interval = 300;
                                    timer_sendcfg.Start();
                                    isMouseOverControl = false;
                                }
                                catch
                                {
                                    showmsg("错了");
                                    isMouseOverControl = false;
                                }
                            }
                        }
                        break;
                    default: { break; }
                }

                switch (HFR_comboBox.SelectedItem.ToString())
                {
                    case "1. HFR0":
                        strtmp_sub0 = "";
                        strtmp_sub0 += Data_out();
                        break;
                    case "2. HFR1":
                        strtmp_sub1 = "";
                        strtmp_sub1 += Data_out();
                        break;
                    case "3. HFR2":
                        strtmp_sub2 = "";
                        strtmp_sub2 += Data_out();
                        break;
                    case "4. HFR3":
                        strtmp_sub3 = "";
                        strtmp_sub3 += Data_out();
                        break;
                    default:
                        break;
                }
            }
        }

        private void HFR_comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (flag == 1)
            {
                DMR_dataGridView_r.ClearSelection();
                DMR_dataGridView_g.ClearSelection();
                DMR_dataGridView_b.ClearSelection();
                this.DMR_dataGridView_r.Rows.Clear();
                this.DMR_dataGridView_g.Rows.Clear();
                this.DMR_dataGridView_b.Rows.Clear();
                string test = str_concat(strtmp, HFR_comboBox.SelectedItem.ToString()); // 频率分割
                string strtmp_sub = rgb_concat(test, comboBox6.SelectedItem.ToString()); // 亮度分割
                string[] arrtmp = strtmp_sub.Split(new Char[] { ',' });
                Data_show(arrtmp);
                cell_flag = 0;
            }
        }

        private void btnSaveDMRCfg_Click_1(object sender, EventArgs e)
        {
            if (flag == 1)
            {
                string output = "", str_out = ""; ;
                string output_sub = "";
                string output_sub1 = "";
                int len;
                int i = 0;
                int j = 0;
                string filePath = "";

                try
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Title = "选择文件保存位置";
                    saveFileDialog.DefaultExt = "txt";

                    saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
                    saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        filePath += saveFileDialog.FileName;
                    }
                }
                catch { Console.WriteLine("没有选择文件"); }

                if (!string.IsNullOrEmpty(filePath))
                {
                    textBox3.Text = filePath;
                    output += string.IsNullOrEmpty(strtmp_sub0) ? str_concat(strtmp, "1. HFR0") : strtmp_sub0;
                    output += string.IsNullOrEmpty(strtmp_sub1) ? str_concat(strtmp, "2. HFR1") : strtmp_sub1;
                    output += string.IsNullOrEmpty(strtmp_sub2) ? str_concat(strtmp, "3. HFR2") : strtmp_sub2;
                    output += string.IsNullOrEmpty(strtmp_sub3) ? str_concat(strtmp, "4. HFR3") : strtmp_sub3;
                    output += strtmp.Substring(5184, 12096);

                    for (i = 0; i < output.Length / (128 * 3); i++)
                    {
                        if(i == 0 )
                            output_sub += "[77]-" + output.Substring(i * 128 * 3, 128 * 3 - 1) + "\r";
                        else
                            output_sub += "[78]-" + output.Substring(i * 128 * 3, 128 * 3 - 1) + "\r";
                    }

                    output_sub1 = output_sub.Replace(',', '-');

                    output_sub1 = head_str + output_sub1 + end_str;

                    using (StreamWriter writer = new StreamWriter(filePath, false, System.Text.Encoding.UTF8))
                    {
                        writer.Write(output_sub1.TrimEnd());
                        MessageBox.Show("保存成功！地址：" + filePath, "保存完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    //string Directory = Path.GetDirectoryName(filePath) + "\\H2.txt";
                    //Console.WriteLine(Directory);
                    //for (int a = 0; a < 45; a++)
                    //{
                    //    str_out += strtmp.Substring(a * 128 * 3, 128 * 3 - 1) + "\r\n";
                    //}
                    //using (StreamWriter writer = new StreamWriter(Directory, false, System.Text.Encoding.UTF8))
                    //{
                    //    writer.Write(str_out);
                    //}
                }
            }
        }

        private void btnReload_Demura_File_Click_1(object sender, EventArgs e)
        {

        }

        private void TrackBar_DMRcfg_Scroll(object sender, MouseEventArgs e)
        {
            if(flag == 1)
            {
                btnPreProcess.PerformClick();
                btnSendCFG.PerformClick();
            }
        }

        private void timer_sendcfg_Tick(object sender, EventArgs e)
        {
            timer_sendcfg.Stop();
            btnPreProcess.PerformClick();
            btnSendCFG.PerformClick();
        }
        //-----------------------end line-------------------
    }
}